package com.chixing.work;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.entity.OrderBase;
import com.chixing.entity.OrderDetail;
import com.chixing.service.IOrderBaseService;
import com.chixing.service.IOrderDetailService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

// OrderTimeoutListener.java
// OrderTimeoutListener.java
@Component
public class OrderTimeoutListener {

    @Autowired
    private IOrderBaseService orderBaseService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @RabbitListener(queues = "delay_queue")
    public void handleOrderTimeout(Integer orderId, Channel channel, Message message) {
        try {
            // 查询订单状态
            OrderBase order = orderBaseService.getOrderById(orderId);

            // 如果订单还是待支付状态，则取消订单
            if (order != null && order.getStatues() == 0) { // 0表示待支付
                // 更新订单状态为已取消
                order.setStatues(3); // 3表示已取消
                order.setUpdateTime(LocalDateTime.now());
                orderBaseService.updateOrder(order);

                // 同时更新订单详情状态
                QueryWrapper<OrderDetail> detailQueryWrapper = new QueryWrapper<>();
                detailQueryWrapper.eq("order_id", orderId);
                List<OrderDetail> orderDetails = orderDetailService.list(detailQueryWrapper);
                for (OrderDetail detail : orderDetails) {
                    detail.setStatues(3); // 3表示已取消
                    detail.setUpdateTime(LocalDateTime.now());
                    orderDetailService.updateById(detail);
                }
            }

            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            System.err.println("处理订单超时消息失败，订单ID: " + orderId + ", 错误: " + e.getMessage());
            e.printStackTrace();

            try {
                // 发生异常时拒绝消息并不重新入队
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ioException) {
                System.err.println("确认消息失败: " + ioException.getMessage());
                ioException.printStackTrace();
            }
        }
    }

}

